package com.zhengxing.jienci.service;

import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.social.security.SocialUser;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Component;

import com.zhengxing.jienci.authentication.mobile.SmsDetailsService;
import com.zhengxing.jienci.common.pojo.SysUser;
import com.zhengxing.jienci.common.util.FastJsonUtil;
import com.zhengxing.jienci.common.util.IdGenerateUtil;
import com.zhengxing.jienci.repository.SysUserMapper;

/**
 * 该类都是基于内存的 ，后期会改变为db,需要去数据库中查询
 */
@Component("userDetailsService")
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService, SocialUserDetailsService, SmsDetailsService {

	@Autowired
	private SysUserMapper sysUserMapper;

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	private boolean autoRegister = true;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		log.info("当前登陆用户名为:{}", username);
		SysUser sysUser = sysUserMapper.getUserByUsername(username);
		if(sysUser == null) {
			throw new UsernameNotFoundException("该用户不存在");
		}
		return User.builder().username(username).password(sysUser.getPassword()).authorities("ROLE_ADMIN").build();
	}

	@Override
	public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
		SysUser sysUser = sysUserMapper.selectById(userId);
		if (sysUser == null && autoRegister) {
			sysUser = createUser(sysUser, "", userId);
			redisTemplate.opsForValue().set("login_user_" + userId, FastJsonUtil.toJSON(sysUser), 10, TimeUnit.MINUTES);
		}
		return new SocialUser(sysUser.getUsername(), sysUser.getPassword(), true, true, true, true,
				AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
	}

	@Override
	public UserDetails loadUserByMobile(String mobile) throws UsernameNotFoundException {
		SysUser sysUser = sysUserMapper.getUserByMobile(mobile);
		if (sysUser == null && autoRegister) {
			sysUser = createUser(sysUser, mobile, IdGenerateUtil.getId());
			sysUserMapper.insert(sysUser);
		}
		log.info("用户{}正在使用手机进行认证登录", sysUser.getNickname());
		return User.builder().username(sysUser.getUsername()).password(sysUser.getPassword()).authorities("ROLE_ADMIN")
				.build();

	}

	private SysUser createUser(SysUser sysUser, String mobile, String userId) {
		sysUser = new SysUser();
		sysUser.setId(userId);
		sysUser.setUsername(userId);
		sysUser.setNickname(mobile);
		sysUser.setPassword(passwordEncoder.encode("123456"));
		sysUser.setMobile(mobile);
		sysUser.setStatus(0);
		sysUser.setCreateTime(new Date());
		sysUser.setUpdateTime(new Date());
		return sysUser;

	}
}
